package com.koushikdutta.async.http.body;

import com.koushikdutta.async.ByteBufferList;
import com.koushikdutta.async.DataEmitter;
import com.koushikdutta.async.DataSink;
import com.koushikdutta.async.LineEmitter;
import com.koushikdutta.async.LineEmitter.StringCallback;
import com.koushikdutta.async.NullDataCallback;
import com.koushikdutta.async.Util;
import com.koushikdutta.async.callback.CompletedCallback;
import com.koushikdutta.async.callback.ContinuationCallback;
import com.koushikdutta.async.callback.DataCallback;
import com.koushikdutta.async.future.Continuation;
import com.koushikdutta.async.http.AsyncHttpRequest;
import com.koushikdutta.async.http.Multimap;
import com.koushikdutta.async.http.libcore.RawHeaders;
import com.koushikdutta.async.http.server.BoundaryEmitter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.UUID;

public class MultipartFormDataBody extends BoundaryEmitter implements AsyncHttpRequestBody<Multimap> {
    String contentType = "multipart/form-data";
    RawHeaders formData;
    ByteBufferList last;
    String lastName;
    LineEmitter liner;
    MultipartCallback mCallback;
    private ArrayList<Part> mParts;
    int totalToWrite;
    int written;

    public interface MultipartCallback {
        void onPart(Part part);
    }

    public void parse(DataEmitter emitter, CompletedCallback completed) {
        setDataEmitter(emitter);
        setEndCallback(completed);
    }

    void handleLast() {
        if (this.last != null) {
            if (this.formData == null) {
                this.formData = new RawHeaders();
            }
            this.formData.add(this.lastName, this.last.peekString());
            this.lastName = null;
            this.last = null;
        }
    }

    protected void onBoundaryEnd() {
        super.onBoundaryEnd();
        handleLast();
    }

    protected void onBoundaryStart() {
        final RawHeaders headers = new RawHeaders();
        this.liner = new LineEmitter();
        this.liner.setLineCallback(new StringCallback() {
            public void onStringAvailable(String s) {
                if ("\r".equals(s)) {
                    MultipartFormDataBody.this.handleLast();
                    MultipartFormDataBody.this.liner = null;
                    MultipartFormDataBody.this.setDataCallback(null);
                    Part part = new Part(headers);
                    if (MultipartFormDataBody.this.mCallback != null) {
                        MultipartFormDataBody.this.mCallback.onPart(part);
                    }
                    if (MultipartFormDataBody.this.getDataCallback() != null) {
                        return;
                    }
                    if (part.isFile()) {
                        MultipartFormDataBody.this.setDataCallback(new NullDataCallback());
                        return;
                    }
                    MultipartFormDataBody.this.lastName = part.getName();
                    MultipartFormDataBody.this.last = new ByteBufferList();
                    MultipartFormDataBody.this.setDataCallback(new DataCallback() {
                        public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
                            bb.get(MultipartFormDataBody.this.last);
                        }
                    });
                    return;
                }
                headers.addLine(s);
            }
        });
        setDataCallback(this.liner);
    }

    public MultipartFormDataBody(String[] values) {
        for (String value : values) {
            String[] splits = value.split("=");
            if (splits.length == 2 && "boundary".equals(splits[0])) {
                setBoundary(splits[1]);
                return;
            }
        }
        report(new Exception("No boundary found for multipart/form-data"));
    }

    public void write(AsyncHttpRequest request, final DataSink sink, final CompletedCallback completed) {
        if (this.mParts == null) {
            sink.end();
            return;
        }
        Continuation c = new Continuation(new CompletedCallback() {
            public void onCompleted(Exception ex) {
                completed.onCompleted(ex);
            }
        });
        Iterator i$ = this.mParts.iterator();
        while (i$.hasNext()) {
            final Part part = (Part) i$.next();
            c.add(new ContinuationCallback() {
                public void onContinue(Continuation continuation, CompletedCallback next) throws Exception {
                    part.getRawHeaders().setStatusLine(MultipartFormDataBody.this.getBoundaryStart());
                    byte[] bytes = part.getRawHeaders().toHeaderString().getBytes();
                    Util.writeAll(sink, bytes, next);
                    MultipartFormDataBody multipartFormDataBody = MultipartFormDataBody.this;
                    multipartFormDataBody.written += bytes.length;
                }
            }).add(new ContinuationCallback() {
                public void onContinue(Continuation continuation, CompletedCallback next) throws Exception {
                    long partLength = part.length();
                    if (partLength >= 0) {
                        MultipartFormDataBody multipartFormDataBody = MultipartFormDataBody.this;
                        multipartFormDataBody.written = (int) (((long) multipartFormDataBody.written) + partLength);
                    }
                    part.write(sink, next);
                }
            }).add(new ContinuationCallback() {
                public void onContinue(Continuation continuation, CompletedCallback next) throws Exception {
                    byte[] bytes = "\r\n".getBytes();
                    Util.writeAll(sink, bytes, next);
                    MultipartFormDataBody multipartFormDataBody = MultipartFormDataBody.this;
                    multipartFormDataBody.written += bytes.length;
                }
            });
        }
        c.add(new ContinuationCallback() {
            static final /* synthetic */ boolean $assertionsDisabled = (!MultipartFormDataBody.class.desiredAssertionStatus());

            public void onContinue(Continuation continuation, CompletedCallback next) throws Exception {
                byte[] bytes = MultipartFormDataBody.this.getBoundaryEnd().getBytes();
                Util.writeAll(sink, bytes, next);
                MultipartFormDataBody multipartFormDataBody = MultipartFormDataBody.this;
                multipartFormDataBody.written += bytes.length;
                if (!$assertionsDisabled && MultipartFormDataBody.this.written != MultipartFormDataBody.this.totalToWrite) {
                    throw new AssertionError();
                }
            }
        });
        c.start();
    }

    public String getContentType() {
        if (getBoundary() == null) {
            setBoundary("----------------------------" + UUID.randomUUID().toString().replace("-", ""));
        }
        return "multipart/form-data; boundary=" + getBoundary();
    }

    public boolean readFullyOnRequest() {
        return false;
    }

    public int length() {
        if (getBoundary() == null) {
            setBoundary("----------------------------" + UUID.randomUUID().toString().replace("-", ""));
        }
        int length = 0;
        Iterator i$ = this.mParts.iterator();
        while (i$.hasNext()) {
            Part part = (Part) i$.next();
            part.getRawHeaders().setStatusLine(getBoundaryStart());
            if (part.length() == -1) {
                return -1;
            }
            length = (int) (((long) length) + ((part.length() + ((long) part.getRawHeaders().toHeaderString().getBytes().length)) + ((long) "\r\n".length())));
        }
        length += getBoundaryEnd().getBytes().length;
        this.totalToWrite = length;
        return length;
    }
}
